<template>
  <CustomHeader />
  <div class="min-h-screen flex items-center justify-center bg-gray-100 px-4">
    <div class="bg-white shadow-lg rounded-2xl w-full max-w-md p-6">
      <LogoImg />
      <form @submit.prevent="handleUpload">
        <div class="mb-4">
          <label for="excel" class="block mb-1 text-sm font-medium text-gray-700">Upload Excel</label>
          <button
            type="button"
            @click="triggerFileInput"
            class="w-full px-3 py-2 border rounded-xl text-left bg-gray-50 hover:bg-gray-100"
          >
            Click to select file
          </button>
          <input
            id="excel"
            ref="fileInput"
            type="file"
            accept=".xlsx"
            class="hidden"
            @change="onFileChange"
            required
          />
        </div>

        <div v-if="fileName" class="text-sm mb-4 text-gray-600">Selected file: {{ fileName }}</div>

        <div v-if="errorMessage" class="text-red-500 text-sm mb-4">
          {{ errorMessage }}
        </div>

        <button
          type="submit"
          :disabled="!file || loading"
          class="w-full py-2 bg-green-600 hover:bg-green-700 text-white rounded-xl disabled:opacity-50"
        >
          {{ loading ? 'Uploading...' : 'Upload File' }}
        </button>
      </form>
    </div>
  </div>
</template>

<script setup>
import CustomHeader from '@/components/CustomHeader.vue';
import LogoImg from '@/components/LogoImg.vue';
import { ref } from 'vue';

const file = ref(null);
const fileName = ref('');
const errorMessage = ref('');
const loading = ref(false);
const fileInput = ref(null);

function triggerFileInput() {
  fileInput.value?.click();
}

function onFileChange(e) {
  const selected = e.target.files[0];
  // biome-ignore lint/complexity/useOptionalChain: <explanation>
  if (selected && selected.name.endsWith('.xlsx')) {
    file.value = selected;
    fileName.value = selected.name;
    errorMessage.value = '';
  } else {
    errorMessage.value = 'Please select a valid Excel file (.xlsx)';
    file.value = null;
    fileName.value = '';
  }
}

function handleUpload() {
  if (!file.value) return;

  loading.value = true;
  setTimeout(() => {
    alert(`File "${fileName.value}" uploaded successfully!`);
    loading.value = false;
    file.value = null;
    fileName.value = '';
  }, 1500);
}
</script>

<style scoped>
/* Optional styling extensions */
</style>
